<template>
	<div>
		<el-dialog
			:title="formTitle"
			:visible.sync="visible"
			append-to-body
			width="80%"
			:before-close="dialogBeforeClose"
			:destroy-on-close="true"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
			@closed="handlerClosed"
		>
			<el-form
				ref="form"
				:model="formData"
				:rules="rules"
				label-width="80px"
				:inline="false"
				size="normal"
			>
				<el-form-item label="标题" prop="title">
					<el-input v-model="formData.title" clearable />
				</el-form-item>

				<el-form-item label="简述" prop="sketch">
					<el-input v-model="formData.sketch" type="textarea" clearable />
				</el-form-item>

				<el-form-item label="发布内容" prop="articleJson" clearable>
					<Tinymce
						v-if="visible"
						v-model="formData.articleJson"
						:height="300"
						placeholder="在这里输入文字"
						:images-upload-handler="imagesUploadHandler"
					/>
				</el-form-item>

				<el-form-item label="发布类型" prop="articleType" clearable>
					<el-select
						v-model="formData.articleType"
						placeholder="请选择"
						clearable
					>
						<el-option
							v-for="item in articleTypeOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
				</el-form-item>

				<el-form-item label="是否发布" prop="publish">
					<el-radio-group v-model="formData.publish">
						<el-radio
							v-for="item in dictPublishData"
							:key="item.value"
							:value="item.value"
							:label="item.value"
							>{{ item.label }}</el-radio
						>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="标签" prop="tagList">
					<el-select v-model="formData.tagList" multiple placeholder="请选择">
						<el-option
							v-for="item in tagTypeOptions"
							:key="item.id"
							:label="item.tagData"
							:value="item.id"
						/>
					</el-select>
				</el-form-item>

				<el-form-item>
					<el-button type="primary" size="medium" @click="onSubmit">
						确定
					</el-button>
					<el-button size="medium" @click="handlerCancel"> 取消 </el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>

<script>
import { fileURLConfig } from '@/http/upLoad'
export default {
	props: {
		dictPublish: {
			type: Array,
			default: () => {
				return []
			},
		},
		tagData: {
			type: Array,
			default: () => {
				return []
			},
		},

		articleType: {
			type: Array,
			default: () => {
				return []
			},
		},
		curData: {
			type: Object,
			default: () => {
				return {}
			},
		},
		curDataCopy: {
			type: Object,
			default: () => {
				return {}
			},
		},
		visible: {
			type: Boolean,
			default: false,
		},
		formTitle: {
			type: String,
			default: '',
		},
	},
	data() {
		return {
			rules: {
				title: [{ required: true, message: '请输入标题', trigger: 'blur' }],

				articleJson: [
					{ required: true, message: '请输入发布内容', trigger: 'change' },
				],
				articleType: [
					{ required: true, message: '请选择是否发布', trigger: 'change' },
				],
				publish: [
					{ required: true, message: '请选择发布类型', trigger: 'change' },
				],
				// tagList: [{ required: true, message: '请选择标签', trigger: 'change' }],
			},
			imgCacheList: [],
		}
	},
	computed: {
		formData() {
			return this.curData || {}
		},
		//发布的字典数据
		dictPublishData() {
			return this.dictPublish
		},
		//标签类型
		tagTypeOptions() {
			return this.tagData
		},

		//文章发布类型
		articleTypeOptions() {
			return this.articleType
		},
	},

	methods: {
		async getImgSrc(str) {
			let imgReg = /<img.*?(?:>|\/>)/gi //匹配图片中的img标签
			let srcReg = /src=[\\'\\"]?([^\\'\\"]*)[\\'\\"]?/i // 匹配图片中的src
			let arr = str.match(imgReg) //筛选出所有的img
			let srcArr = []
			if (arr && Array.isArray(arr) && arr.length > 0) {
				// debugger
				for (let i = 0; i < arr.length; i++) {
					let src = arr[i].match(srcReg)
					// 获取图片地址
					srcArr.push(src[1])
				}
			}
			return srcArr
		},
		imagesUploadHandler(blobInfo, success) {
			let formData = new FormData()
			formData.append('file', blobInfo.blob(), blobInfo.filename())
			formData.append('folderName', fileURLConfig.articleFolderName)
			const reader = new FileReader()
			reader.readAsDataURL(blobInfo.blob())
			reader.onload = () => {
				const ImgBase64 = reader.result
				// 实现预览，实际是拿到图片的base64数据去挂在到图片的src上
				this.imgCacheList.push({
					url: fileURLConfig.uploadPicture,
					method: 'post',
					data: formData,
					ImgBase64,
				})
				success(ImgBase64)
			}
		},
		handlerClosed() {},
		dialogBeforeClose() {
			this.$emit('update:visible', false)
			this.$emit('update:curData', {})
			this.$emit('update:curDataCopy', {})
			this.handlerResetFields()
		},
		async onSubmit() {
			this.$refs.form.validate(async valid => {
				if (valid) {
					this.formData.id = this.formData.id == '-1' ? null : this.formData.id
					// console.log(this.formData.id, 77777)
					let obj = this._.cloneDeep(this.formData)
					let removeList = [] //*需要删除的

					if (!this.formData.id) {
						let arr1 = await this.getImgSrc(this.formData.articleJson)
						let res = [] // * 需要上传的图片
						arr1.forEach(i => {
							let e = this.imgCacheList.find(j => j.ImgBase64 === i)
							if (e) {
								res.push(e)
							}
						})
						// // console.log(res, 222)
						let regObj = {}
						if (res.length > 0) {
							res.forEach(async (i, index) => {
								let { url, method } = i
								let { data } = await this.$axios({
									url,
									method,
									data: i.data,
								})
								if (data.head.code == 200) {
									regObj[i.ImgBase64] = data.data[0].httpImageUrl
								}
								if (index === res.length - 1) {
									obj.articleJson = this.formData.articleJson.replace(
										/<img [^>]*src=['"]([^'"]+)[^>]*>/gi,
										function (match, capture) {
											return `<img src='${regObj[capture]}'/>`
										},
									)
									this.$emit('submit', obj, removeList)
								}
							})
						} else {
							this.$emit('submit', obj, removeList)
						}
					} else {
						let arr1 =
							(await this.getImgSrc(this.curDataCopy.articleJson || '')) || []
						let arr2 =
							(await this.getImgSrc(this.formData.articleJson || '')) || []
						// console.log(arr1, arr2)
						// debugger
						let addList = [] //*需要上传的图片
						arr2.forEach(i => {
							let e = this.imgCacheList.find(j => j.ImgBase64 === i)
							if (e) {
								addList.push(e)
							}
						})
						// debugger
						arr1.forEach(i => {
							let e = arr2.find(k => i !== k)
							if (!e) {
								// console.log(i, 33333333)
								removeList.push(i)
							}
						})
						let regObj = {}
						if (addList.length > 0) {
							addList.forEach(async (i, index) => {
								let { url, method } = i
								let { data } = await this.$axios({
									url,
									method,
									data: i.data,
								})
								if (data.head.code == 200) {
									regObj[i.ImgBase64] = data.data[0].httpImageUrl
								}
								if (index === addList.length - 1) {
									obj.articleJson = this.formData.articleJson.replace(
										/<img [^>]*src=['"]([^'"]+)[^>]*>/gi,
										function (match, capture) {
											return `<img src='${regObj[capture]}'/>`
										},
									)
									// console.log(obj.articleJson, 88)
									this.$emit('submit', obj, removeList)
								}
							})
						} else {
							this.$emit('submit', obj, removeList)
						}
					}
				}
			})
			// this.$emit('submit', this.formData)
			// this.imgCacheList = []
			// } else {
			// 	return false
			// }
			// })
		},
		async handlerCancel() {
			// this.handlerResetFields()
			// if (!this.formData.id) {
			// this.$emit('removeImgList', [...this.imgCacheList])
			this.imgCacheList = []
			// } else {
			// let arr1 = await this.getImgSrc(this.curDataCopy.articleJson)
			// let arr2 = await this.getImgSrc(this.curData.articleJson)
			// // // console.log(arr1, arr2)
			// let res = []
			// arr2.forEach(i => {
			// 	let e = arr1.find(j => j !== i)
			// 	if (e) {
			// 		res.push(e)
			// 	}
			// })
			// res = Array.from(new Set([...res, ...this.imgCacheList]))
			// this.$emit('removeImgList', [...res])
			// this.imgCacheList = []
			// }
			this.dialogBeforeClose()
		},
		handlerResetFields() {
			this.$nextTick(() => {
				this.$refs['form'].clearValidate()
			})
		},
	},
}
</script>

<style lang="scss" scoped></style>
